package school30.io;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

/**
 * Class for all files connections
 * @author asamarin97
 */
public class FileManager extends FileConnector{
    boolean init;
    
    Hashtable mountingPoints;

    /**
     * Creates file manager
     * @param mp - mounting points - Hashtable (String, FileConnector)
     */
    public FileManager(Hashtable mp)
    {
        this.mountingPoints = mp;
    }

    /**
     * Mount filesystem
     * @param path - mounting path
     * @param con - file connector
     */
    public void mount(String path, FileConnector con)
    {
        mountingPoints.put(path, con);
    }

    /**
     * Umount filesystem
     * @param path - mounting path
     */
    public void umount(String path)
    {
        mountingPoints.remove(path);
    }

    private String getConnector(File path)
    {
        return (String) path.path.elementAt(0);
    }

    public FileReader openRead(File path) {
        String ph = getConnector(path);
        FileConnector con = (FileConnector) mountingPoints.get(ph);
        return con.openRead(path.removeFirst());
    }

    public FileWriter openWrite(File path) {
        String ph = getConnector(path);
        FileConnector con = (FileConnector) mountingPoints.get(ph);
        return con.openWrite(path.removeFirst());
    }

    public long size(File path) {
        String ph = getConnector(path);
        FileConnector con = (FileConnector) mountingPoints.get(ph);
        if (path.isSubRoot())
            return -2;
        else
            return con.size(path.removeFirst());
    }

    public String[] folderContents(File path) {
        if (path.pathLength() == 0)
        {
            String[] mm = new String[mountingPoints.size()];
            Enumeration e = mountingPoints.keys();
            int i = 0;
            while (e.hasMoreElements())
            {
                mm[i] = (String) e.nextElement();
                i++;
            }
            return mm;
        }
        String ph = getConnector(path);
        FileConnector con = (FileConnector) mountingPoints.get(ph);
        return con.folderContents(path.removeFirst());
    }

    public void deleteFile(File path) {
        String ph = getConnector(path);
        FileConnector con = (FileConnector) mountingPoints.get(ph);
        con.deleteFile(path.removeFirst());
    }

    public void createFolder(File path) {
        String ph = getConnector(path);
        FileConnector con = (FileConnector) mountingPoints.get(ph);
        con.createFolder(path.removeFirst());
    }

    public boolean isFolder(File path) {
        String ph = getConnector(path);
        FileConnector con = (FileConnector) mountingPoints.get(ph);
        return con.isFolder(path.removeFirst());
    }
}